<?php

namespace app\common\model\marketing;

use addons\xyb\XypHelper;
use app\common\model\Circle;
use app\common\model\Goods;
use app\common\model\Scenic;
use app\common\model\User;
use think\Model;


class MarketingCoupons extends Model
{

    // 表名
    protected $name = 'marketing_coupons';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    public static $type_list = [
        1 => '优惠劵',
        2 => '满减劵',
        3 => '折扣劵',
        4 => '立减劵',
    ];

    public static function getAdminLists()
    {
        $keyword = request()->param('keyword', '');
        $type = request()->param('type/a');
        $grant_platform = request()->param('grant_platform/a');
        $grant_status = request()->param('grant_status/a');
        $field = 'id,name,amount,type,satisfy_amount,discount_rate,get_limit,effective_date,effective_days,grant_platform,
        expiration_method,describe,deadline_start,deadline_end,grant_status,createtime,receive_total,grant_total,use_total';
        $query = self::field($field);
        if ($keyword) {
            $query->where(function ($query) use ($keyword) {
                $query->where('id', 'like', "%{$keyword}%")
                    ->whereOr('name', 'like', "%{$keyword}%")
                    ->whereOr('describe', 'like', "%{$keyword}%")
                    ->whereOr('amount', 'like', "%{$keyword}%")
                    ->whereOr('satisfy_amount', 'like', "%{$keyword}%")
                    ->whereOr('discount_rate', 'like', "%{$keyword}%")
                    ->whereOr('grant_total', 'like', "%{$keyword}%");

            });
        }
        if ($type = XypHelper::stringToArray($type)) {
            $query->whereIn('type', $type);
        }
        if ($grant_platform = XypHelper::stringToArray($grant_platform)) {
            $query->whereIn('grant_platform', $grant_platform);
        }
        if ($grant_status = XypHelper::stringToArray($grant_status)) {
            $query->whereIn('grant_status', $grant_status);
        }

        $lists = $query->order('id desc')->paginate(10);
        return $lists;
    }

    public static function getDetails($coupons_id)
    {
        $field = '*';
        $details = self::field($field)->find($coupons_id);
        if (!$details) {
            return false;
        }
        $details->effective_date = date('Y-m-d', $details->effective_date);
        if ($details->grant_method == 2 && $details->grant_agent_id) {
            if ($grant_agent_ids = XypHelper::stringToArray($details->grant_agent_id)) {
                $details->grant_agent_id = Circle::whereIn('id', $grant_agent_ids)->column('name');
            }
        }
        if ($details->grant_method == 3 && $details->grant_users_id) {
            if ($grant_users_id = XypHelper::stringToArray($details->grant_users_id)) {
                $details->grant_users_id = User::whereIn('id', $grant_users_id)->column('nickname');
            }
        }
        if ($details->grant_ticket_method == 2 && $details->grant_ticket_business_id) {
            if ($grant_ticket_business_id = XypHelper::stringToArray($details->grant_ticket_business_id)) {
                $details->grant_ticket_business_id = Scenic::whereIn('id', $grant_ticket_business_id)->column('scenic_name');
            }
        }
        if ($details->grant_ticket_method == 3 && $details->grant_ticket_product_id) {
            if ($grant_ticket_product_id = XypHelper::stringToArray($details->grant_ticket_product_id)) {
                $details->grant_ticket_product_id = Goods::whereIn('id', $grant_ticket_product_id)->column('goods_name');
            }
        }
        return $details;
    }

    public static function getCouponsDetails($coupons_id)
    {
        $marketing_coupons = MarketingCoupons::where('id', $coupons_id)->find();
        if (!$marketing_coupons) {
            return false;
        }
        $lists_maps = [
            'id' => $marketing_coupons['id'],
            'name' => $marketing_coupons['name'],
            'type_text' => MarketingCoupons::getTypeList($marketing_coupons['type']),
            'type' => $marketing_coupons['type'],
            'get_limit' => $marketing_coupons['get_limit'],
            'discount_rate' => $marketing_coupons['discount_rate'],
            'satisfy_amount' => $marketing_coupons['satisfy_amount'],
            'marketing_coupons' => $marketing_coupons,
            'amount' => $marketing_coupons['amount'],
            'describe' => $marketing_coupons['describe'],
            'coupons_text' => MarketingCoupons::getCouponsAmountMsg($marketing_coupons),
            'platform_text' => MarketingCoupons::getGrantPlatformList($marketing_coupons),
            'usage_text' => MarketingCoupons::getCouponsGrantMethodMsg($marketing_coupons),
            'grant_platform' => $marketing_coupons['grant_platform'],
            'deadline_text' => MarketingCoupons::getExpirationMsg($marketing_coupons),
            'amount_text' => MarketingCoupons::getAmountTipsMsg($marketing_coupons)
        ];
        return $lists_maps;
    }

    public static function updateStatus($coupons_id, $status)
    {
        $coupons = self::get($coupons_id);
        if (!$coupons) {
            return false;
        }
        $coupons->grant_status = $status;
        $coupons->save();
        return true;
    }

    public function getDeadlineStartAttr($value, $data)
    {
        return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }

    public function getDeadlineEndAttr($value, $data)
    {
        return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }

    public function getCreatetimeAttr($value, $data)
    {
        return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }

    public static function getTypeList($value)
    {
        $type_items = ['1' => '优惠劵', '2' => '满减劵', '3' => '折扣劵', '4' => '立减劵'];
        return $type_items[$value];
    }

    public static function getGrantPlatformList($rows)
    {
        if($rows['grant_platform'] == 2){
            return '互助劵'; //$grant_errand_method = [1=>'互助劵', 2=>'互助劵',3=>'互助劵'];
        }elseif ($rows['grant_platform'] == 3){
            return $rows['grant_ticket_method'] == 1?'通用劵':'商品劵';
        } else {
            return '通用劵';
        }
    }
    public static function getExpirationMsg($rows)
    {
        if ($rows['expiration_method'] == 1) {
            $expiration_date = date('Y-m-d', $rows['effective_date']) . '前有效';
        } else {
            $expiration_date = '领取后' . $rows['effective_days'] . '小时有效';
        }
        return $expiration_date;
    }

    public static function getAmountTipsMsg($rows)
    {
        $expiration_date = '';
        if ($rows['type'] == 1) {
            if ($rows['satisfy_amount'] > 0) {
                $expiration_date = '满' . (float)$rows['satisfy_amount'] . '元可用';
            } else {
                $expiration_date = '无门槛';
            }
        } elseif ($rows['type'] == 2) {
            if ($rows['satisfy_amount'] > 0) {
                $expiration_date = '满' . (float)$rows['satisfy_amount'] . '元减' . (float)$rows['amount'] . '元';
            } else {
                $expiration_date = '无门槛';
            }

        } elseif ($rows['type'] == 3) {
            if ($rows['satisfy_amount'] > 0) {
                $expiration_date = '满' . (float)$rows['satisfy_amount'] . '元打' . (float)$rows['discount_rate'] . '折';
            } else {
                $expiration_date = '无门槛';
            }
        } elseif ($rows['type'] == 4) {
            $max_amount = 0;
            if ($random_rule = XypHelper::formatJsonStringToArray($rows['random_rule'])) {
                array_map(function ($item) use (&$max_amount) {
                    $max_amount = (float)$item['amount'] > (float)$max_amount ? (float)$item['amount'] : $max_amount;
                }, $random_rule);
            }
            if ($rows['satisfy_amount'] > 0) {
                $expiration_date = '满' . (float)$rows['satisfy_amount'] . '元可用' . ($max_amount ? ',最高减' . $max_amount . '元' : '');
            } else {
                $expiration_date = '无门槛' . ($max_amount ? ',最高减' . $max_amount . '元' : '');
            }
        }
        return $expiration_date;
    }

    public static function getCouponsAmountMsg($rows)
    {
        $expiration_date = '';
        if ($rows['type'] == 1) {
            $expiration_date = ((float)$rows['amount']) . '元';
        } elseif ($rows['type'] == 2) {
            $expiration_date = (float)$rows['amount'] . '元';
        } elseif ($rows['type'] == 3) {
            $expiration_date = (float)$rows['discount_rate'] . '折';
        } elseif ($rows['type'] == 4) {
            $expiration_date = '随机减';
        }
        return $expiration_date;
    }

    public static function getCouponsGrantMethodMsg($rows)
    {
        $expiration_date = '';
        if($rows['grant_platform'] == 2){
            $grant_errand_method = [1=>'通用劵', 2=>'【帮我送】可用',3=>'【帮我取】可用'];
            $expiration_date = $grant_errand_method[$rows['grant_errand_method']];
        }elseif ($rows['grant_platform'] == 3){
            if ($rows['grant_ticket_method'] == 2) {
                if ($grant_ticket_business_ids = XypHelper::stringToArray($rows['grant_ticket_business_id'])) {
                    if(count($grant_ticket_business_ids) > 1){
                        $expiration_date = "适用".count($grant_ticket_business_ids)."个商家";
                    } else {
                        $expiration_date = '仅限'.Scenic::where('id', $rows['grant_ticket_business_id'])->value('scenic_name');
                    }
                }
            }elseif ($rows['grant_ticket_method'] == 3) {
                if ($grant_ticket_product_ids = XypHelper::stringToArray($rows['grant_ticket_product_id'])) {
                    if(count($grant_ticket_product_ids) > 1){
                        $expiration_date = "适用".count($grant_ticket_product_ids)."个商品";
                    } else {
                        if($business_id = Goods::where('id', $grant_ticket_product_ids[0])->value('scenic_id')){
                            $expiration_date = '仅限'.Scenic::where('id', $business_id)->value('scenic_name');
                        }
                    }
                }
            }else{
                $expiration_date = '通用劵';
            }
            if(is_array($expiration_date)){
                $expiration_date = XypHelper::arrayToString($expiration_date);
            }
        } else {
            $expiration_date = '通用劵';
        }
        return $expiration_date;
    }

    public static function getUsersCanClaimedMarketingCoupons($user_id, $circle_id)
    {
        $field = 'id,name,amount,type,satisfy_amount,discount_rate,get_limit,effective_date,effective_days,
        expiration_method,grant_platform,describe,random_rule,receive_start_time,receive_end_time,
        use_start_time,use_end_time,grant_errand_method,grant_ticket_method,grant_ticket_business_id,grant_ticket_product_id';
        $lists = self::field($field)->where('get_method', 1)
            ->where('grant_status', 2)
            ->where(function ($query) use ($user_id, $circle_id) {
                $query->where('grant_method', 1)->whereOr(function ($q) use ($circle_id) {
                    $q->where('grant_method', 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                })->whereOr(function ($q) use ($user_id) {
                    $q->where('grant_method', 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            })
            ->whereIn('grant_platform', [1, 2, 3])
            ->where('receive_start_time', '<', time())->where('receive_end_time', '>', time())
            ->whereRaw('grant_total > receive_total')
            ->limit(10)
            ->select();
        if (!$lists) {
            return [];
        }
        $lists_maps = [];
        foreach ($lists as $k => $v) {
            if ($v['effective_date'] > 0 && $v['effective_date'] < time()) {
                continue;
            }
            $receive_stated = self::getCouponsUsersIsReceiveStated($user_id, $v);
            if (!$receive_stated['get_limit']) {
                continue;
            }
            $lists_maps[$k] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'type_text' => self::getTypeList($v['type']),
                'type' => $v['type'],
                'get_limit' => $v['get_limit'],
                'discount_rate' => $v['discount_rate'],
                'satisfy_amount' => $v['satisfy_amount'],
                'amount' => $v['amount'],
                'describe' => $v['describe'],
                'grant_platform' => $v['grant_platform'],
                'receive_time' => [date('Y-m-d H:i', $v['receive_start_time']), date('Y-m-d H:i', $v['receive_end_time'])],
                'use_time' => [date('Y-m-d H:i', $v['use_start_time']), date('Y-m-d H:i', $v['use_end_time'])],
                'coupons_text' => self::getCouponsAmountMsg($v),
                'usage_text' => MarketingCoupons::getCouponsGrantMethodMsg($v),
                'platform_text' => MarketingCoupons::getGrantPlatformList($v),
                'deadline_text' => self::getExpirationMsg($v),
                'amount_text' => self::getAmountTipsMsg($v),
                'receive_stated' => $receive_stated
            ];
        }
        return array_slice($lists_maps, 0, 3);
    }

    public static function getCouponsUsersReceiveLists($user_id, $circle_id, $type, $page, $limit, $grant_platform = 0)
    {
        if ($type >= 2) {
            return self::getCouponsUsersReceiveAlreadyLists($user_id, $circle_id, $page, $limit, $type, $grant_platform);
        }
        $field = 'id,name,amount,type,satisfy_amount,discount_rate,get_limit,effective_date,effective_days,
        expiration_method,describe,grant_platform,random_rule,use_start_time,use_end_time,grant_agent_id,
        grant_users_id,grant_errand_method,grant_ticket_method,grant_ticket_business_id,grant_ticket_product_id';
        $query = self::field($field)->where('grant_status', 2)
            ->where(function ($query) use ($user_id, $circle_id) {
                $query->where('grant_method', 1)->whereOr(function ($q) use ($circle_id) {
                    $q->where('grant_method', 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                })->whereOr(function ($q) use ($user_id) {
                    $q->where('grant_method', 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            });
        if ($grant_platform) {
            $query->where('grant_platform', $grant_platform);
        }
        $lists = $query->where('receive_start_time', '<', time())
            ->where('receive_end_time', '>', time())
            ->whereRaw('grant_total > receive_total')
            ->order('id desc')
            ->paginate($limit, false, ['page' => $page]);

        if (!$lists) {
            return [];
        }
        $lists_maps = [];
        foreach ($lists as $k => $v) {
            if ($v['effective_date'] > 0 && $v['effective_date'] < time()) {
                continue;
            }
            $receive_stated = self::getCouponsUsersIsReceiveStated($user_id, $v);
//            if (!$receive_stated['get_limit']) {
//                continue;
//            }
            $lists_maps[$k] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'type_text' => self::getTypeList($v['type']),
                'type' => $v['type'],
                'get_limit' => $v['get_limit'],
                'discount_rate' => $v['discount_rate'],
                'satisfy_amount' => $v['satisfy_amount'],
                'amount' => $v['amount'],
                'describe' => $v['describe'],
                'grant_platform' => $v['grant_platform'],
                'coupons_text' => self::getCouponsAmountMsg($v),
                'platform_text' => MarketingCoupons::getGrantPlatformList($v),
                'usage_text' => MarketingCoupons::getCouponsGrantMethodMsg($v),
                'deadline_text' => self::getExpirationMsg($v),
                'amount_text' => self::getAmountTipsMsg($v),
                'use_system_product' => self::usingSystemProducts($v),
                'receive_stated' => $receive_stated
            ];
        }
        return ['total' => count($lists_maps), 'list' => array_values($lists_maps)];
    }

    public static function getCouponsUsersReceiveAlreadyLists($user_id, $circle_id, $page, $limit, $type = 0, $grant_platform = 0)
    {
        $use_status = request()->param('use_status', 0);
        $field = 'marketing_coupons.id,marketing_coupons.name,marketing_coupons.amount,marketing_coupons.type,
        marketing_coupons.satisfy_amount,marketing_coupons.discount_rate,marketing_coupons.get_limit,
        marketing_coupons.effective_date,marketing_coupons.effective_days,marketing_coupons.expiration_method,marketing_coupons.describe,
        marketing_coupons.grant_platform,yx_users_marketing_coupons.deadline_time,yx_users_marketing_coupons.use_status,
        marketing_coupons.grant_ticket_business_id,marketing_coupons.grant_ticket_product_id,marketing_coupons.grant_errand_method,
        marketing_coupons.grant_ticket_method,yx_users_marketing_coupons.id as users_coupons_id,
        yx_users_marketing_coupons.createtime as receive_time,yx_users_marketing_coupons.coupons_id,marketing_coupons.random_rule';
        $query = UsersMarketingCoupons::join(
            'marketing_coupons', 'yx_users_marketing_coupons.coupons_id=marketing_coupons.id', 'left'
        )->field($field)->where('yx_users_marketing_coupons.user_id', $user_id);
        if ($grant_platform) {
            $query->whereIn('marketing_coupons.grant_platform', [1, intval($grant_platform)]);
        }
//        if ($use_status) {
//            if (in_array($use_status, [1, 2])) {
//                $query->where('yx_users_marketing_coupons.use_status', $use_status - 1);
//            } else {
//                $query->where('yx_users_marketing_coupons.deadline_time', '<', time());
//            }
//        }
        if ($type > 2) {
            if ($type == 3) {
                $query->where('yx_users_marketing_coupons.use_status', 1);
            } else if ($type == 4) {
                $query->where('yx_users_marketing_coupons.deadline_time', '<', time());
            }
        } else {
            $query->where('yx_users_marketing_coupons.use_status', 0)
                ->where('yx_users_marketing_coupons.deadline_time', '>', time());
        }

        $lists = $query->order('yx_users_marketing_coupons.id desc')
            ->paginate($limit, false, ['page' => $page]);
        if (!$lists) {
            return [];
        }
        $lists_maps = [];
        foreach ($lists as $k => $v) {
            $lists_maps[$k] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'type_text' => self::getTypeList($v['type']),
                'type' => $v['type'],
                'get_limit' => $v['get_limit'],
                'discount_rate' => $v['discount_rate'],
                'satisfy_amount' => $v['satisfy_amount'],
                'amount' => $v['amount'],
                'describe' => $v['describe'],
                'grant_platform' => $v['grant_platform'],
                'coupons_text' => self::getCouponsAmountMsg($v),
                'platform_text' => MarketingCoupons::getGrantPlatformList($v),
                'usage_text' => MarketingCoupons::getCouponsGrantMethodMsg($v),
                'deadline_text' => self::getExpirationMsg($v),
                'amount_text' => self::getAmountTipsMsg($v),
                'receive_stated' => self::getCouponsUsersAlreadyReceiveStated($user_id, $v),
                'use_system_product' => self::usingSystemProducts($v)
            ];
        }
        return ['total' => $lists->total(), 'list' => $lists_maps];
    }

    public static function getCouponsUsersReceiveBefore($coupons_id, $user_id, $circle_id)
    {
        $field = '*';
        $coupons = self::field($field)->where('id', $coupons_id)->where('grant_status', 2)
            ->where(function ($query) use ($user_id, $circle_id) {
                $query->where('grant_method', 1)->whereOr(function ($q) use ($circle_id) {
                    $q->where('grant_method', 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                })->whereOr(function ($q) use ($user_id) {
                    $q->where('grant_method', 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            })->where('receive_start_time', '<', time())->where('receive_end_time', '>', time())
            ->whereRaw('grant_total > receive_total')->find();
        return $coupons;
    }

    public static function getCouponsUsersIsReceiveStated($user_id, $coupons)
    {
        $users_receive_total = UsersMarketingCoupons::getCouponsUsersReceiveTotal($user_id, $coupons['id']);
        if ($users_receive_total >= $coupons['get_limit']) {
            return ['stated' => 5, 'msg' => '去使用', 'get_limit' => 0];
        }
        return ['stated' => 1, 'msg' => '可领取', 'get_limit' => ($coupons['get_limit'] - $users_receive_total)];
    }

    public static function getCouponsUsersAlreadyReceiveStated($user_id, $coupons)
    {
        if ($coupons['deadline_time'] < time()) {
            return ['stated' => 2, 'msg' => '已过期'];
        }
        if ($coupons['use_status'] > 0) {
            return ['stated' => 2, 'msg' => '已使用'];
        }
        return ['stated' => 5, 'msg' => '去使用'];
    }

    public static function usingSystemProducts($coupons)
    {
        $response = [
            'type' => (int)$coupons['grant_platform'],
            'page' => '',
            'is_jump' => true,
        ];
        /* 互助系统 */
        if ($response['type'] == 2) {
            switch ($coupons['grant_errand_method']) {
                case 1:
                    $response['page'] = "/pagesC/video/index?currentActive=2";
                    break;
                case 2:
                    $response['page'] = "/pagesD/form/form";
                    break;
                case 3:
                    $response['page'] = "/pagesD/form/form1";
                    break;
            }
        } else { //商城
            $response['is_jump'] = false;
            switch ($coupons['grant_ticket_method']) {
                case 2://商家
                    if ($business_ids = XypHelper::stringToArray($coupons['grant_ticket_business_id'])) {
                        $response['is_jump'] = true;
                        if (count($business_ids) > 1) {
                            $response['page'] = "/pagesD/coupon/coupon_goods_list?ids={$coupons['id']}&title=" . count($business_ids) . "个可使用的商家";
                        } else {
                            $response['page'] = "/pagesA/scenic/ScenicDetail?scenicId={$coupons['grant_ticket_business_id']}&binduid=0";
                        }
                    }
                    break;
                case 3://产品
                    if ($product_ids = XypHelper::stringToArray($coupons['grant_ticket_product_id'])) {
                        $response['is_jump'] = true;
                        if (count($product_ids) > 1) {
                            $where = ['id' => ['in', $product_ids], 'goods_status' => 1];
                            $scenic_ids = array_filter(array_unique(Goods::where($where)->column('scenic_id')));
                            $response['page'] = "/pagesD/coupon/coupon_goods_list?ids={$coupons['id']}&title=" . count($scenic_ids) . "个可使用的商家";
                        } else {
                            if ($business_id = Goods::where('id', $product_ids[0])->value('scenic_id')) {
                                $response['page'] = "/pagesA/scenic/ScenicDetail?scenicId={$business_id}&binduid=0";
                            } else {
                                $response['is_jump'] = false;
                            }
                        }
                    }
                    break;
            }
        }
        return $response;
    }

    public static function getUsersProductReceiveCoupons($user_id, $grant_platform, $business_id, $product_id = 0)
    {
        $field = 'id,name,amount,type,satisfy_amount,discount_rate,get_limit,effective_date,effective_days,
        expiration_method,describe,grant_platform,random_rule,grant_method,grant_agent_id,grant_users_id,
        grant_errand_method,grant_ticket_method,grant_ticket_business_id,grant_ticket_product_id';
        $query = MarketingCoupons::field($field)->whereIn('grant_platform', [1, $grant_platform]);

        $product_ids = Goods::where('scenic_id', $business_id)->where('goods_status', 1)->column('id');

        if (!$product_ids) {
            return [];
        }
        if ($grant_platform == 3 && $business_id && $product_ids) {
            $query->whereIn("grant_ticket_method", [1, 2, 3]);
            $query->where(function ($query) use ($grant_platform, $business_id, $product_ids) {
                $query->whereOr(function ($q) use ($business_id) {
                    $q->whereRaw("FIND_IN_SET('{$business_id}', grant_ticket_business_id)");
                })->whereOr(function ($q) use ($product_ids) {
                    foreach ($product_ids as $product_id) {
                        $q->whereOr(function ($r) use ($product_id) {
                            $r->whereRaw("FIND_IN_SET('{$product_id}', grant_ticket_product_id)");
                        });
                    }
                });
            });
        }
        $lists = $query->where('receive_start_time', '<', time())->where('receive_end_time', '>', time())
            ->order('id desc')->select();
        if (!$lists) {
            return [];
        }
        $lists_maps = [];
        foreach ($lists as $k => $v) {
            if ($v['effective_date'] > 0 && $v['effective_date'] < time()) {
                continue;
            }
            $receive_stated = self::getCouponsUsersIsReceiveStated($user_id, $v);
            $lists_maps[$k] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'type_text' => MarketingCoupons::getTypeList($v['type']),
                'type' => $v['type'],
                'get_limit' => $v['get_limit'],
                'discount_rate' => $v['discount_rate'],
                'satisfy_amount' => $v['satisfy_amount'],
                'amount' => $v['amount'],
                'describe' => $v['describe'],
                'grant_platform' => $v['grant_platform'],
                'coupons_text' => MarketingCoupons::getCouponsAmountMsg($v),
                'platform_text' => MarketingCoupons::getGrantPlatformList($v),
                'usage_text' => MarketingCoupons::getCouponsGrantMethodMsg($v),
                'deadline_text' => MarketingCoupons::getExpirationMsg($v),
                'amount_text' => MarketingCoupons::getAmountTipsMsg($v),
                'coupons_amount_tips' => self::getCouponsMaxAmountItems($v),
                'receive_stated' => $receive_stated,
                'grant_ticket_product_id'   => $v['grant_ticket_product_id']
            ];
        }
        return array_values($lists_maps);
    }


    public static function getUsersProductIdsReceiveCoupons($business_id, $product_id = 0)
    {
        $field = 'id,name,amount,type,satisfy_amount,discount_rate,get_limit,effective_date,effective_days,
        expiration_method,describe,grant_platform,random_rule,grant_method,grant_agent_id,grant_users_id,
        grant_errand_method,grant_ticket_method,grant_ticket_business_id,grant_ticket_product_id';
        $query = MarketingCoupons::field($field)->whereIn('grant_platform', [1, 3]);

        if ($business_id && $product_id) {
            $query->where(function ($query) use ($business_id, $product_id) {
                $query->whereOr(function ($q) use ($business_id) {
                    $q->whereRaw("FIND_IN_SET('{$business_id}', grant_ticket_business_id)");
                })->whereOr(function ($q) use ($product_id) {
                    $q->whereRaw("FIND_IN_SET('{$product_id}', grant_ticket_product_id)");
                });
            });
        }
        $lists = $query->where('receive_start_time', '<', time())
            ->where('receive_end_time', '>', time())
            ->order('id desc')->select();
        if (!$lists) {
            return ['max_coupons' => '', 'coupons_num' => 0];
        }
        $lists_maps = [];
        foreach ($lists as $k => $v) {
            if ($v['effective_date'] > 0 && $v['effective_date'] < time()) {
                continue;
            }
            $lists_maps[$k] = [
                'coupons_amount_tips' => self::getCouponsMaxAmountItems($v),
            ];
        }
        $max_amount = 0;
        $last_max_amount = '';
        foreach ($lists_maps as $k=>$v){
            $coupons_amount_tips = $v['coupons_amount_tips'];
            if($coupons_amount_tips['discount'] && $coupons_amount_tips['discount'] > $max_amount){
                $max_amount = $last_max_amount = $v['coupons_amount_tips']['discount'].'元';
            } else {
                $last_max_amount = $coupons_amount_tips['discount_rate'].'折';
            }
        }
        if(!$max_amount){
            $max_amount = $last_max_amount;
        }
        return [
            'max_coupons' => '最高优惠'.$max_amount,
            'coupons_num'      => count($lists),
        ];
    }

    public static function getUsersBusinessIdsReceiveCoupons($business_id)
    {
        $field = 'id,name,amount,type,satisfy_amount,discount_rate,get_limit,effective_date,effective_days,
        expiration_method,describe,grant_platform,random_rule,grant_method,grant_agent_id,grant_users_id,
        grant_errand_method,grant_ticket_method,grant_ticket_business_id,grant_ticket_product_id';
        $query = MarketingCoupons::field($field)->whereIn('grant_platform', [1, 3]);
        $product_ids = Goods::where('scenic_id', $business_id)->where('goods_status', 1)->column('id');

        if (!$product_ids) {
            return [];
        }
        if ($business_id && $product_ids) {
            $query->where(function ($query) use ($business_id, $product_ids) {
                $query->whereOr(function ($q) use ($business_id) {
                    $q->whereRaw("FIND_IN_SET('{$business_id}', grant_ticket_business_id)");
                })->whereOr(function ($q) use ($product_ids) {
                    foreach ($product_ids as $product_id) {
                        $q->whereOr(function ($r) use ($product_id) {
                            $r->whereRaw("FIND_IN_SET('{$product_id}', grant_ticket_product_id)");
                        });
                    }
                });
            });
        }
        $lists = $query->where('receive_start_time', '<', time())
            ->where('receive_end_time', '>', time())
            ->order('id desc')->select();
        if (!$lists) {
            return ['max_coupons' => '', 'coupons_num' => 0];
        }
        $lists_maps = [];
        foreach ($lists as $k => $v) {
            if ($v['effective_date'] > 0 && $v['effective_date'] < time()) {
                continue;
            }
            $lists_maps[$k] = [
                'coupons_amount_tips' => self::getCouponsMaxAmountItems($v),
            ];
        }
        $max_amount = 0;
        $last_max_amount = '';
        foreach ($lists_maps as $k=>$v){
            $coupons_amount_tips = $v['coupons_amount_tips'];
            if($coupons_amount_tips['discount'] && $coupons_amount_tips['discount'] > $max_amount){
                $max_amount = $last_max_amount = $v['coupons_amount_tips']['discount'].'元';
            } else {
                $last_max_amount = $coupons_amount_tips['discount_rate'].'折';
            }
        }
        if(!$max_amount){
            $max_amount = $last_max_amount;
        }
        return [
            'max_coupons' => '最高优惠'.$max_amount,
            'coupons_num'      => count($lists),
        ];
    }
    public static function getUsersAssistanceReceiveCoupons($users_id, $errand_method)
    {
        $coupons_ids = UsersMarketingCoupons::where('user_id', $users_id)
            ->where('use_status', 0)
            ->where('grant_status', 1)
            ->where('deadline_time', '>', time())
            ->whereIn('use_platform', [1, 2])
            ->column('coupons_id');
        if (!$coupons_ids) {
            return [];
        }
        $field = 'id,name,amount,type,satisfy_amount,discount_rate,get_limit,effective_date,effective_days,
        expiration_method,describe,grant_platform,random_rule,grant_errand_method,grant_ticket_method,
        grant_ticket_business_id,grant_ticket_product_id';
        $query = MarketingCoupons::field($field)->whereIn('id', $coupons_ids)
            ->whereIn('grant_platform', [1, 2]);
        $errand_method += 1;
        $query->where(function ($query) use ($errand_method) {
            $query->whereIn('grant_errand_method', [1, intval($errand_method)]);
        });

        $lists = $query->where('use_start_time', '<', time())->where('use_end_time', '>', time())
            ->order('id desc')->select();

        if (!$lists) {
            return [];
        }
        $lists_maps = [];
        $max_amount = 0;
        $last_max_amount = '';
        foreach ($lists as $k => $v) {
            if ($v['effective_date'] > 0 && $v['effective_date'] < time()) {
                continue;
            }
            $coupons_amount_tips = self::getCouponsMaxAmountItems($v);
            if ($coupons_amount_tips['discount'] && $coupons_amount_tips['discount'] > $max_amount) {
                $max_amount = $coupons_amount_tips['discount'];
                $last_max_amount = $coupons_amount_tips['tips'];
            }
            if ($v['type'] == 4) {
                $last_max_amount = $coupons_amount_tips['tips'];
            }
            $lists_maps[$k] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'type_text' => MarketingCoupons::getTypeList($v['type']),
                'type' => $v['type'],
                'get_limit' => $v['get_limit'],
                'discount_rate' => $v['discount_rate'],
                'satisfy_amount' => $v['satisfy_amount'],
                'amount' => $v['amount'],
                'describe' => $v['describe'],
                'grant_platform' => $v['grant_platform'],
                'coupons_text' => MarketingCoupons::getCouponsAmountMsg($v),
                'platform_text' => MarketingCoupons::getGrantPlatformList($v),
                'usage_text' => MarketingCoupons::getCouponsGrantMethodMsg($v),
                'deadline_text' => MarketingCoupons::getExpirationMsg($v),
                'amount_text' => MarketingCoupons::getAmountTipsMsg($v)
            ];
        }
        return ['lists' => $lists_maps, 'max_amount' => $last_max_amount];
    }

    public static function getCouponsMaxAmount($rows)
    {
        $expiration_date = '';
        if ($rows['type'] == 1) {
            if ($rows['satisfy_amount'] > 0) {
                $expiration_date = '满' . (float)$rows['satisfy_amount'] . '元可用,优惠' . (float)$rows['amount']. '元';
            } else {
                $expiration_date = '无门槛';
            }
        } elseif ($rows['type'] == 2) {
            if ($rows['satisfy_amount'] > 0) {
                $expiration_date = '满' . (float)$rows['satisfy_amount'] . '元减' . (float)$rows['amount'] . '元';
            } else {
                $expiration_date = '无门槛';
            }

        } elseif ($rows['type'] == 3) {
            if ($rows['satisfy_amount'] > 0) {
                $expiration_date = '满' . (float)$rows['satisfy_amount'] . '元打' . (float)$rows['discount_rate'] . '折';
            } else {
                $expiration_date = '无门槛';
            }
        } elseif ($rows['type'] == 4) {
            $max_amount = 0;
            if ($random_rule = XypHelper::formatJsonStringToArray($rows['random_rule'])) {
                array_map(function ($item) use (&$max_amount) {
                    $max_amount = (float)$item['amount'] > (float)$max_amount ? (float)$item['amount'] : $max_amount;
                }, $random_rule);
            }
            if ($rows['satisfy_amount'] > 0) {
                $expiration_date = '满' . (float)$rows['satisfy_amount'] . '元可用' . ($max_amount ? ',最高减' . $max_amount . '元' : '');
            } else {
                $expiration_date = '无门槛' . ($max_amount ? ',最高减' . $max_amount . '元' : '');
            }
        }
        return $expiration_date;
    }

    public static function getCouponsMaxAmountItems($rows)
    {
        $expiration_date = [
            'satisfy_amount' => (float)$rows['satisfy_amount'],
            'discount' => (float)$rows['amount'],
            'discount_rate' => (float)$rows['discount_rate'],
            'type' => (int)$rows['type'],
            'tips' => ''
        ];
        $expiration_date['tips'] = '优惠' . (float)sprintf('%.2f', $expiration_date['discount']);
        if ($rows['type'] == 3) {
            $expiration_date['discount'] = 0;
            $expiration_date['tips'] = '优惠' . ($rows['discount_rate']) . '折';
        } elseif ($rows['type'] == 4) {
            $max_amount = 0;
            if ($random_rule = XypHelper::formatJsonStringToArray($rows['random_rule'])) {
                array_map(function ($item) use (&$max_amount) {
                    $max_amount = (float)$item['amount'] > (float)$max_amount ? (float)$item['amount'] : $max_amount;
                }, $random_rule);
            }
            $expiration_date['discount'] = $max_amount;
            $expiration_date['tips'] = '优惠' . (float)sprintf('%.2f', $max_amount) . '元';
        }
        return $expiration_date;
    }

}
